package base.pattern;

import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

public class PatternDemo {
    public static void main(String[] args) {
        Pattern pattern = Pattern.compile("honou?r");

        String caesarUK = "For Brutus is an honourable man";
        Matcher mUK = pattern.matcher(caesarUK);

        String caesarUS = "For Brutus is an honorable man";
        Matcher mUS = pattern.matcher(caesarUS);

        System.out.println("Matches UK spelling? " + mUK.find());
        System.out.println("Matches US spelling? " + mUS.find());


        // 注意，必须使用\\，因为我们需要的是字面量\，而Java使用单个\转义字符
        String pStr = "\\d"; // 一个数字
        String text = "Apollo 13";
        Pattern p = Pattern.compile(pStr);
        Matcher m = p.matcher(text);
        System.out.print(pStr + " matches " + text + "? " + m.find());
        System.out.println(" ; match: " + m.group());

        pStr = "[a..zA..Z]"; // 任意一个字母
        p = Pattern.compile(pStr);
        m = p.matcher(text);
        System.out.print(pStr + " matches " + text + "? " + m.find());
        System.out.println(" ; match: " + m.group());

        // 任意个字母，但字母只能在a到j之间，大小写不限
        pStr = "([a..jA..J]*)";
        p = Pattern.compile(pStr);
        m = p.matcher(text);
        System.out.print(pStr + " matches " + text + "? " + m.find());
        System.out.println(" ; match: " + m.group());

        text = "abacab";
        pStr = "a....b"; // a和b之间有四个字符
        p = Pattern.compile(pStr);
        m = p.matcher(text);
        System.out.print(pStr + " matches " + text + "? " + m.find());
        System.out.println(" ; match: " + m.group());

        // Java8的asPredicate方法
        String pStr1 = "\\d"; // 一个数字
        Pattern pattern1 = Pattern.compile(pStr1);
        List<String> ls = Arrays.asList("Cat", "Dog", "Ice-9", "99 Luftballoons");
        List<String> containDigits = ls.stream()
                .filter(pattern1.asPredicate())
                .collect(Collectors.toList());
        System.out.println(containDigits);
    }
}
